;
(function (w) {
  var iframeBus = {
    chat: {
      origin: '',
      window: {}
    },
    pc: {
      origin: '',
      window: {}
    }
  }

  function postMessageTo(frameMark, data) {
    iframeBus[frameMark].window.postMessage(data, iframeBus[frameMark].origin)
  }

  function ScrmChat(opts) {
    ScrmChat.publicApis = {}
    ScrmChat.publicApis.showChatWindow = opts.showChatWindow
    ScrmChat.publicApis.hideChatWindow = opts.hideChatWindow
    var chatId = opts.containerId
    var body, container, theframe, options = {},
      theWin
    container = document.querySelector('#' + chatId)

    var ORIGIN = window.location.origin
    var OTHER_ORIGIN = opts.msgOrigin
    // jaron ↓
    iframeBus.chat.origin = opts.msgOrigin
    // jaron ↑

    if (!container) {
      console.error('请指定节点')
      return
    } else {
      if (container.children && container.children.length) {
        console.error('当前配置节点，含有子节点')
        return
      }
    }

    // authentication
    options.token = opts.token

    // base infos
    options.sName = opts.username || ''
    options.sId = opts.id || ''

    // base options
    options.debug = opts.debug || false
    options.api_server = opts.api_server || ''
    options.env = opts.env

    function createFrame() {
      theframe = document.createElement('iframe')
      // 正式的地址先隐藏，使用本地的进行测试
      theframe.src = (opts.baseUrl || '') + 'index.html?_=' + new Date().getTime()

      theframe.style.border = 'none'
      theframe.style.width = '981px'
      theframe.style.height = '640px'

      container.appendChild(theframe)
    }

    function receiveChatMsg(event) {
      console.log(event)
      var msgObj = event.data
      if (event.origin !== OTHER_ORIGIN) {
        return
      }
      console.log(msgObj)
      if (msgObj.name === 'chat-ready') {
        theWin = event.source
        // jaron ↓
        iframeBus.chat.window = event.source
        // jaron ↑
        sendConfig()
      }

      if (msgObj.name === 'update-msg-num') {
        if (opts.updateMsgNum && typeof opts.updateMsgNum === 'function') {
          console.log('msgObj.params.count', msgObj.params.count)
          opts.updateMsgNum(msgObj.params.count)
        }
      }

      if (msgObj.name === 'customer-detail') {
        if (opts.onUserDetail && typeof opts.onUserDetail === 'function') {
          opts.onUserDetail(msgObj.params.id)
        }
      }

      if (msgObj.name === 'add-appoint') {
        if (opts.addAppoint && typeof opts.addAppoint === 'function') {
          opts.addAppoint(msgObj.params.id)
        }
      }

      if (msgObj.name === 'add-member') {
        console.debug('plugin.js addMember 方法触发')
        if (opts.addMember && typeof opts.addMember === 'function') {
          opts.addMember()
        }
      }

      // ↓ 添加患者
      if (msgObj.name === 'add-patient') {
        console.log('外层收到消息了！')
        console.debug('plugin.js 添加患者方法触发')
        if (opts.addPatient && typeof opts.addPatient === 'function') {
          console.log('收到的数据是：')
          console.log(msgObj)
          opts.addPatient(msgObj.params.fanInfo)
        }
      }
      // ↑ 添加患者
      // ↓ 添加imToken
      if (msgObj.name === 'im-token') {
        console.log('外层收到消息了！')
        if (!window.fromImChat) {
          window.fromImChat = {}
        }
        window.fromImChat.imToken = msgObj.params.token
      }
      // ↑ 添加imToken
    }

    function postMessage(data) {
      // 以下纯为本地测试
      console.log('调用postMessage了！！')
      console.log('OTHER_ORIGIN是：')
      console.log(OTHER_ORIGIN)
      if (!theWin) {
        theWin = document.getElementsByTagName('iframe')[0].contentWindow
      }
      // 以上纯为本地测试
      theWin.postMessage(data, OTHER_ORIGIN)
    }

    function sendConfig() {
      var config = {
        name: 'chat-config',
        data: {
          type: 'chat',
          sId: options.sId.toString(),
          sName: options.sName,
          token: options.token,
          api_server: options.api_server,
          msgOrigin: ORIGIN,
          env: options.env
        }
      }
      postMessage(config)
    }

    this.startChat = function (userId) {
      var data = {
        name: 'startChat',
        data: {
          id: userId
        }
      }
      postMessage(data)
    }

    this.hideChat = function () {
      var data = {
        name: 'hideChat'
      }
      postMessage(data)
    }
    // 以下均为新增
    this.refreshAllUserInfo = function () {
      var data = {
        name: 'refreshAllUserInfo'
      }
      postMessage(data)
    }
    // 以上均为新增

    createFrame()
    if (!window._xcrm_im_event_init) {
      window._xcrm_im_event_init = true
      window.addEventListener('message', receiveChatMsg, false)
    }

    // call back functions
    options.onUserDetail = opts.onUserDetail
    options.updateMsgNum = opts.updateMsgNum

    w.ScrmConf = options
  }

  function ScrmPc(opts) {
    var chatId = opts.containerId
    var body, container, theframe, options = {},
      theWin
    container = document.querySelector('#' + chatId)

    //TODO: config origin validation
    var origin = {
      container: window.location.origin,
      inner: [opts.msgOrigin, 'https://mall-back.lctest.cn:444', 'https://mall-back.linkedcare.cn:444', 'https://mall-back.lctest.cn', 'https://mall-back.linkedcare.cn', 'https://scrm-apps.lctest.cn', 'https://scrm-apps.linkedcare.cn'],
      current: null
    }

    // jaron ↓
    iframeBus.pc.origin = opts.msgOrigin
    // jaron ↑

    if (!container) {
      console.error('请指定节点')
      return
    } else {
      if (container.children && container.children.length) {
        console.error('当前配置节点，含有子节点')
        return
      }
    }
    // authentication
    options.token = opts.token
    options.api_server = opts.msgOrigin || ''
    options.env = opts.env
    options.path = opts.path
    this.options = options

    function receiveMsg(event) {
      var msgObj = event.data
      if (origin.inner.indexOf(event.origin) < 0) {
        return
      }

      if (msgObj.name === 'pc-ready') {
        theWin = event.source
        // jaron ↓
        iframeBus.pc.window = event.source
        // jaron ↑
        sendConfig()
      }

      if (msgObj.name === 'pc-start-chat') {
        msgObj.name = 'startChat'
        ScrmChat.publicApis.showChatWindow()
        postMessageTo(msgObj.frameMark, msgObj)
      }
    }

    function postMessage(data) {
      // theWin.postMessage(data, OTHER_ORIGIN)
      theWin.postMessage(data, '*')
    }

    function sendConfig() {
      var config = {
        name: 'pc-config',
        data: {
          type: 'pc',
          token: options.token,
          api_server: options.api_server,
          msgOrigin: origin.container,
          env: options.env
        }
      }
      postMessage(config)
    }

    if (!window._xcrm_pc_event_init) {
      window._xcrm_pc_event_init = true
      window.addEventListener('message', receiveMsg, false)
    }

    function mapEnv(env) {
      switch (env) {
        case 'kouqiang':
          return 'kq'
        case 'emei':
          return 'ym'
        case 'quanke':
          return 'qk'
        default:
          return env
      }
    }

    function createFrame() {
      var params = new URLSearchParams()
      params.append('_', Date.now())
      if (options.path) {
        params.append('path', options.path)
      }
      theframe = document.createElement('iframe')
      theframe.src = (opts.baseUrl || '') + 'index.html?' + params.toString()
      // theframe.src = 'https://scrm-apps.lctest.cn?_=' + new Date().getTime() + '&token=' + options.token + '&env=' + mapEnv(options.env)
      theframe.style.border = 'none'
      theframe.style.width = '100%'
      theframe.style.height = '100%'

      container.appendChild(theframe)
    }

    createFrame()

    function dispatchEvent(event, params) {
      postMessage({
        name: event,
        data: params
      })
    }

    return {
      dispatchEvent: dispatchEvent
    }
  }

  w.ScrmPc = ScrmPc
  w.ScrmChat = ScrmChat
})(window)
